$(function() {
    getComments();

    /* 获取所有评论 */
    function getComments() {
        $.ajax(baseUrl + '/comments', {
            success: res => {
                // console.log(res);
                res.records.forEach(item => {
                    if (item.post.createAt != null) {
                        item.post.createAt = item.post.createAt.split('T')[0].replaceAll('-', '/');
                    }
                    item.state == 1 ? item.state = '已批准' : item.state = '未批准';
                });
                // console.log(res.records);
                let newHtml = template('comments', { commentsList: res.records });
                $('tbody').html(newHtml);
            },
            error: err => {
                console.log('错误信息：', err);
            }
        })
    }

    /* 更改评论状态 */
    $('tbody').on('click', '.approve', function() {
        $.ajax(baseUrl + '/comments/' + $(this).parents().parents().attr('key'), {
            type: 'put',
            data: {
                state: 1
            },
            success: res => {
                getComments();
                alert('已批准');
            },
            async: false,
            error: err => {
                console.log('错误：', err);
            }
        });
    });


    /* 删除评论 */
    $('tbody').on('click', '.dele', function() {
        $.ajax(baseUrl + '/comments/' + $(this).parents().parents().attr('key'), {
            type: 'DELETE',
            success: res => {
                getComments();
                alert('已删除');
            },
            async: false,
            error: err => {
                console.log('错误：', err);
            }
        });
    });

});